package com.durian.base.utils;

import androidx.annotation.StringRes;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.durian.BaseApp;
import com.durian.base.R;
import java.lang.reflect.Field;

/**
 * 说明：ToastUtils
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019-06-17 14:09
 * <p/>
 * 版本：version 1.0
 */
public class ToastUtils {

    private static ToastUtils inject;
    private android.widget.Toast mToast;

    /*禁止实例化*/
    private ToastUtils() {
    }

    public static ToastUtils get() {
        if (inject == null) {
            synchronized (ToastUtils.class) {
                if (inject == null) {
                    inject = new ToastUtils();
                }
            }
        }
        return inject;
    }

    /**
     * 说明：显示短Toast
     *
     * @param msg
     */
    public void shortToast(String msg) {
        showToast(msg, android.widget.Toast.LENGTH_SHORT);
    }


    /**
     * 说明：显示短Toast
     *
     * @param msg
     */
    public void shortToast(@StringRes int msg) {
        shortToast(UIUtils.getString(msg));
    }

    /**
     * 说明：显示Toast
     *
     * @param msg
     * @param time
     * @return
     */
    private void showToast(String msg, int time) {
        if (StringUtils.isEmpty(msg)){
            return;
        }
        Handler handler = BaseApp.handler();
        Context context = BaseApp.getApp();
        if (handler == null || context == null){
            return;
        }
        handler.post(() -> {
            if (mToast != null){
                mToast.cancel();
            }
            mToast = getToast(context,msg,time);
            mToast.show();
        });
    }

    public void successToast(String msg) {
        if (StringUtils.isEmpty(msg)){
            return;
        }
        Handler handler = BaseApp.handler();
        Context context = BaseApp.getApp();
        if (handler == null || context == null){
            return;
        }
        handler.post(() -> {
            if (mToast != null){
                mToast.cancel();
            }
            mToast = getSuccessToast(context,msg,Toast.LENGTH_SHORT);
            mToast.show();
        });
    }

    /**
     * 说明：取消显示Toast
     */
    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }

    /**
     * 说明：显示长Toast
     *
     * @param msg
     */
    public void longToast(String msg) {
        showToast(msg, android.widget.Toast.LENGTH_LONG);
    }

    /**
     * 说明：显示长Toast
     *
     * @param msg
     */
    public void longToast(int msg) {
        longToast(UIUtils.getString(msg));
    }

    private Toast getSuccessToast(Context context,String message,int duration){
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.CENTER, 0, 0);
        View view = LayoutInflater.from(BaseApp.getApp()).inflate(R.layout.base_layout_icon_toast, null);
        TextView tipTv = view.findViewById(R.id.tipTv);
        tipTv.setText(message);
        ImageView tipImg = view.findViewById(R.id.tipImg);
        tipImg.setImageResource(R.drawable.base_succeed_icon_normal);
        toast.setView(view);
        toast.setDuration(duration);
        hookToast(toast);
        return toast;
    }

    private Toast getToast(Context context,String message,int duration){
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.CENTER, 0, 0);
        View view = LayoutInflater.from(BaseApp.getApp()).inflate(R.layout.base_layout_toast, null);
        TextView tipTv = view.findViewById(R.id.tipTv);
        toast.setView(view);
        tipTv.setText(message);
        toast.setDuration(duration);
        hookToast(toast);
        return toast;
    }

    /**
     * 为了解决7.1.x版本toast可以导致crash的问题
     * @param toast
     */
    private static void hookToast(Toast toast) {
        Class<Toast> cToast = Toast.class;
        try {
            //TN是private的
            Field fTn = cToast.getDeclaredField("mTN");
            fTn.setAccessible(true);

            //获取tn对象
            Object oTn = fTn.get(toast);
            //获取TN的class，也可以直接通过Field.getType()获取。
            Class<?> cTn = oTn.getClass();
            Field fHandle = cTn.getDeclaredField("mHandler");

            //重新set->mHandler
            fHandle.setAccessible(true);
            fHandle.set(oTn, new HandlerProxy((Handler) fHandle.get(oTn)));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private static class HandlerProxy extends Handler {

        private Handler mHandler;

        public HandlerProxy(Handler handler) {
            this.mHandler = handler;
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                mHandler.handleMessage(msg);
            } catch (WindowManager.BadTokenException e) {
                //ignore
            }
        }
    }
}
